import * as NSBase from '../NetServiceBase';
import { IAdManager } from '../IManager';
import { IsNull, IsNullOrWhiteSpace, Random } from '../../TYLibrary/Common/GlobalExtend';
import {
	Logger,
	LogLevel,
	T_AD,
	V_AD,
	Wx_Page
	} from '../EntityBase';
import { ManagerBase } from './ManagerBase';

//T_Ad
//NS.QueryAllAd

export class AdManager extends ManagerBase implements IAdManager {
	public QueryAllADUrl: string = "";

	private async _QueryByService() {
		let a = await NSBase.QueryAllAD(this.QueryAllADUrl);
		if (!IsNull(a))
			wx.setStorageSync('AllAd', a);
	}

	public async Init() {
		await this._QueryByService();
	}

	public async AdClick(page: Wx_Page, e: any) {
		Logger.Debug(LogLevel.L1, e);
		if (e.currentTarget.dataset.adinfo) {
			let ad = e.currentTarget.dataset.adinfo as V_AD;
			if (!IsNull(ad)) {
				switch (ad.OPENTYPE) {
					case 'page':
						wx.navigateTo({ url: ad.OPENPARAMETER });
						break;
					case 'showimg':
						if (!IsNullOrWhiteSpace(ad.OPENPARAMETER))
							wx.previewImage({ urls: [ad.OPENPARAMETER + '?t=' + this.m_App.SYS_GetNowDate().getTime()] });
						break;
					case 'open_ad':
						break;
					case 'open_mini_program':
						let data = ad.Programe;
						if (!data.appId.IsNullOrWhiteSpace()) {
							data.success = async (res) => {
								Logger.Debug(LogLevel.L1, res);
							};
							Logger.Debug(LogLevel.L1, data);
							wx.navigateToMiniProgram(data);
						}
						break;
					default:
						//无操作
						break;
				}
			}
		}
	}

	public GetRandomAd(): V_AD {
		let Ads = wx.getStorageSync('AllAd') as Array<T_AD>;
		if (Ads && Ads.length) {
			let r = Ads[Random(0, Ads.length)] as V_AD;
			if (r.OPENTYPE == 'open_mini_program' && !r.OPENPARAMETER.IsNullOrWhiteSpace()) {
				r.Programe = JSON.parse(r.OPENPARAMETER);
			}
			return r;
		}
		return null;
	}

	public GetAds(count): Array<V_AD> {
		let Ads = wx.getStorageSync('AllAd') as Array<T_AD>;
		let rs: Array<V_AD> = [];
		if (Ads && Ads.length) {
			for (let i = 0; i < count; i++) {
				let r = Ads[Random(0, Ads.length)] as V_AD;
				if (r.OPENTYPE == 'open_mini_program' && !r.OPENPARAMETER.IsNullOrWhiteSpace()) {
					r.Programe = JSON.parse(r.OPENPARAMETER);
				}
				rs.push(r);
			}
		}
		return rs;
	}
}
